<template>

<el-tabs type="border-card" @tab-remove="removeTab" :closable="true">
  <el-tab-pane :label="info.name">
    <el-container>
<!--      项目详情-->
      <el-main>

        <baseInfo :info="info" :isdisabled="isdisabled">
        <template #test1>
          <el-form-item label="项目名称">
            <el-input v-model="info.name" disabled></el-input>
          </el-form-item>
        </template>
<!--        预算明细-->

       <template #test2>

         <el-row>
           <el-col :span="6">
             <!--项目城市-->
             <el-form-item label="立项金额" prop="currency">
               <el-input v-model="info.offer" placeholder="立项金额"  disabled></el-input>
             </el-form-item>
           </el-col>

           <el-col :span="6" >
             <el-form-item label="预算金额">
               <el-input v-model="project.offer" placeholder="预算金额" @blur="changeMoney('offer')" :disabled="isdisabled"></el-input>
             </el-form-item>
           </el-col>

           <el-col :span="6">
             <el-form-item label="预算成本">
               <el-input v-model="project.cost" placeholder="预算成本"  disabled></el-input>
             </el-form-item>
           </el-col>
         </el-row>

         <el-row>
           <el-col :span="6">
             <el-form-item label="项目币种" prop="currency">
               <el-select v-model="info.currency" placeholder="项目币种" style="width:100%;" :disabled="isdisabled">
                 <el-option v-for="(v,i) in currencyList" :key="i" :label="v.currency" :value="v.currency" ></el-option>
               </el-select>

             </el-form-item>
           </el-col>
         </el-row>

          <!--预算明细-->
          <el-form-item label="预算明细">
            <el-row type="flex" justify="center">
              <el-col :span="6">标题</el-col>
              <el-col :span="6">金额</el-col>
              <el-col :span="6">备注</el-col>

            </el-row>
            <el-row type="flex" justify="center" v-for="(vv,k) in ysData" :key="k" :gutter="5" class="mt5">
              <el-col :span="6"><el-input v-model="vv.title" placeholder="输入标题" :disabled="vv.disabled" @blur="checkTitle(k)"></el-input></el-col>
              <el-col :span="6"><el-input v-model="vv.money" placeholder="输入金额" @blur="calculateProfit(k)"  @focus="hiddenMoney(vv.money,k)" :disabled="vv.disabled"></el-input></el-col>
              <el-col :span="6"><el-input v-model="vv.desc" placeholder="输入备注"  @focus="handleFocus(vv)" :disabled="vv.disabled"></el-input></el-col>
              <el-col :span="6"><el-button type="danger" v-if="vv.isDel" @click="delYsData(k)">删除</el-button></el-col>
            </el-row>

            <el-row type="flex" justify="center" align="middle" class="mt5" v-if="is_add">
              <el-col :span="12"><el-button type="primary" @click="addYsData">添加预算</el-button></el-col>
            </el-row>
            <div>
              <el-row type="flex" justify="center">
                <el-col :span="6">标题</el-col>
                <el-col :span="6">金额</el-col>
                <el-col :span="6">备注</el-col>

              </el-row>
              <el-row type="flex" justify="center" v-for="(vv,k) in ysData2" :key="k" :gutter="5" class="mt5">
                <el-col :span="6"><el-input v-model="vv.title" placeholder="输入标题" disabled></el-input></el-col>
                <el-col :span="6"><el-input v-model="project[vv.font_price]" placeholder="输入金额" disabled></el-input></el-col>
                <el-col :span="6"><el-input v-model="vv.desc" placeholder="输入备注" disabled></el-input></el-col>
                <el-col :span="6"><el-button type="danger" v-if="vv.isDel" @click="delYsData(k)">删除</el-button></el-col>
              </el-row>
            </div>
          </el-form-item>
          <!--预算明细-->

          <!--      上传附件-->

         <el-form-item v-if="is_upload_file">
               <MyUploadFile
                 ref="ysFile"
                 dir="project_ys"
                 btn-name="附件"
                 :files="fileList"
               ></MyUploadFile>

         </el-form-item>

          <el-form-item label="附件" v-else-if="fileList.length > 0">
            <el-row>
              <el-col :span="18">
                <fileList :file_list="fileList"></fileList>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="销售经理" v-if="is_show">
            <el-select v-model="seller_id" @change="updateSeller" :disabled="roleid != 212">
              <el-option :label="vv.username" :value="vv.id" v-for="(vv,i) in seller_list" :key="i"></el-option>
            </el-select>
          </el-form-item>

          <!--文件上传-->

          <el-form-item label="备注">
            <el-row>
              <el-col :span="18">
                <el-input type="textarea" v-model="project.desc" :disabled="isdisabled"></el-input>
              </el-col>
            </el-row>

          </el-form-item>
          <el-form-item v-if="is_show_btn">
            <el-button type="primary" @click="onSubmit(0)">{{btn}}</el-button>
            <el-button type="primary" @click="onSubmit(1)">保存</el-button>
            <el-button>取消</el-button>
          </el-form-item>

<!--        预算明细-->
        <spForm :form="spform" v-if="hidden" ref="spForm"></spForm>

        </template>

        </baseInfo>

      </el-main>

      <el-footer>
        <history :history="history"></history>
      </el-footer>
    </el-container>
    </el-tab-pane>
    </el-tabs>
</template>

<script>
    import topNavbar from "../common/topNavbar";
    import {getYsDtail,editProjectYs,updateSeller,calculateProfitApi,delYsDetailApi,reCalculateYsProfit} from '@/apilist/Project'
    import history from '../common/history'
    import spForm from "../common/spForm";
    import baseInfo from "../common/baseInfo";
    import fileList from "../common/fileList";
    import uploadFile from "../common/uploadFile.vue";
    import fa from "element-ui/src/locale/lang/fa";
    import MyUploadFile from "../common/MyUploadFile.vue";
    import {getCommonSelect} from '@/apilist/public'

    export default {
        name: "project_edit_ys",
        data(){
            return {
                id: '',
                title:'项目数据',
                path:'/project_list',
                isdisabled:true,
                spform:{
                    note:'',//审批备注
                    newData:'',
                    type: 'ys',
                    fileList: [],
                },
                info: {},
                history: [],
                ysData: [],
                project: {},
                fileList: [],
                hidden: '',
                btn: '',
                seller_id: '',
                is_show: '',
                seller_list: [],
                is_add: true,
                roleid: '',
                is_show_btn: false,
               is_upload_file: false,
              ysData2:[
                {title: '合计金额',font_price:'sub_total',desc: '默认'},
                {title: '税费金额',font_price:'tax',desc: '默认'},
                {title:'总计金额',font_price:'total',desc: '默认'},
                {title: '利润金额',font_price:'profit',desc: '默认'},
                {title: '利润率(%)',font_price:'percent',desc: '默认'},
              ],
              fileParams:{dir:'project_ys',fileList: this.fileList},
              isSubmit: true,
              currencyList: []
            }
        },
        components:{MyUploadFile, uploadFile, topNavbar,history,spForm,baseInfo,fileList},

        methods: {
            onSubmit(is_save){
              if(!this.isSubmit) return false;
              this.isSubmit = false;
               let params = {
                   id: this.id,
                   project: this.project,//预算数据
                   ysData: this.ysData,//预算详情
                   is_save: is_save,
                   baseinfo: this.info,//立项基本信息.,
                   seller_id: this.seller_id,//销售经理
               }
               if(this.is_upload_file){
                 params['file_list'] = this.$refs.ysFile.getNewFileList();//文件
               }

               if(this.hidden){
                 params['spForm'] = {
                   "note": this.$refs.spForm.form.note,
                   "fileList": this.$refs.spForm.getSPFilesComputed(),
                 };
               }
               try {
                 editProjectYs(params).then(res => {
                   this.$message({
                     type: 'success', message: res.msg, onClose: () => {
                       this.getYsDetailData()
                     }
                   })
                 })
               }catch (e) {
                 this.isSubmit = true
                 Promise.reject(e)
                 return false
               }

            },
          hiddenMoney(money,k){
            this.ysData[k]['money'] = this.fun.resetMoney(money) > 0 ? this.fun.fmoney(money) :  "";
          },
          handleFocus(item){
            if(item.desc ==='默认'){
              item.desc = ''
            }
          },
            //计算利润
            calculateProfit(i,isEditYs=false)
            {
                let money = this.ysData[i].money
                money = this.fun.resetMoney(money)
                this.ysData[i].money = this.fun.fmoney(money,2)
                let requestParams = {
                  offer: this.project.offer,
                  rate: this.info.rate,
                  ysData: this.ysData,
                };
                if(isEditYs) requestParams['ysid'] = this.id;
                calculateProfitApi(requestParams).then(res => {
                  this.project.sub_total = res.data.sub_total;
                  this.project.cost = res.data.cost;
                  this.project.total = res.data.total;
                  this.project.percent = res.data.percent;
                  this.project.profit = res.data.profit;
                  this.project.tax = res.data.tax;
                  this.project.offer = res.data.ysmoney;
                });
            },

            //更新销售经理
            updateSeller(){
                updateSeller({id: this.id,seller_id: this.seller_id}).then(res=>{
                    this.$message({type: 'success',message: res.msg,onClose:()=>{
                        this.getYsDetailData()
                      }})
                })
            },
            //修改金额
            changeMoney(field){
                if(this.project.hasOwnProperty(field)){
                    let money =  this.project[field];
                    console.log(money,'money')
                    money = this.fun.resetMoney(money)
                    this.project[field]= this.fun.fmoney(money)
                    if(field == 'offer'){
                        let tax = money * this.info.rate
                        this.project.tax = this.fun.fmoney(tax)
                        this.calculateProfit(0)
                    }
                }

            },
            //添加预算
            addYsData()
            {
                let newYs = {title: '',money: '0.00',desc: '',isDel: true,paytype:4,id: 0,disabled: false}
                this.ysData.push(newYs)

            },

            //删除预算
            delYsData(i){
              const ysid = this.ysData[i]['id'];
              this.$confirm('是否删除预算?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if(ysid){
                  delYsDetailApi({id: ysid}).then(res => {
                    this.$message({
                      type: "success",
                      message: "删除成功",
                      onClose:()=>{
                        let k = this.ysData.length - 1
                        this.calculateProfit(k,true)
                        this.getYsDetailData();// 获取详情
                      }
                    });
                  });
                }else{
                  this.ysData.splice(i,1)
                  let k = this.ysData.length - 1
                  this.calculateProfit(k)
                }
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });
            },
            getYsDetailData(){
                this.id = this.$route.query.id
                getYsDtail({id: this.id}).then(res => {
                    this.info = res.data.baseInfo
                    this.history = res.data.history
                    this.ysData = res.data.ysData
                    this.project = res.data.project
                    this.fileList = res.data.file_list
                    this.hidden = res.data.hidden
                    this.is_show_btn = res.data.is_show_btn
                    this.btn = res.data.btn
                    this.isdisabled = res.data.disable
                    this.spform.newData = res.data
                    this.is_show = res.data.is_show
                    this.is_add = res.data.is_add
                    if(res.data.hasOwnProperty('seller_list')) this.seller_list = res.data.seller_list
                    this.seller_id = res.data.seller_id
                    this.roleid = res.data.roleid;
                    this.is_upload_file = res.data.is_upload_file;
                    this.fileParams['fileList'] = res.data.file_list;
                    this.spform.note = res.data.spForm.note;
                    this.spform.fileList = res.data.spForm.fileList;
                    this.isSubmit = true
                })
            },
            removeTab(){
              this.$router.push({
                path: this.path,
                query: {
                  tab: 1,
                  status: 0
                }
              });
            },
          changeFileList(files){
              this.fileList = files;
          },
          //检查标题
          checkTitle(i){
              const title = this.ysData[i]['title']
            console.log("title", title)
              this.ysData.forEach((v,k)=>{
                if(k !== i && v['title'] == title){
                  this.$message.error("预算"+title + "重复,请检查");
                  return false;
                }
              });
          },

        },
        mounted() {
            this.getYsDetailData()
          getCommonSelect({type: ['currency']}).then(res => {
             this.currencyList = res.data.currency
          })
        }
    }
</script>

<style scoped>
  .mt5{margin-top: 5px;}
</style>
